class Forum < ActiveRecord::Base

  has_many :topics, :dependent => :destroy
  has_many :posts, :through => :topics
  has_many :moderatorships, :dependent => :destroy
  has_many :moderators, :through => :moderatorships, :source => :user
  
  validates_presence_of :name
  
  acts_as_list :scope => :parent_id
  acts_as_tree :order => 'position'
  
  def last_post
    posts.find(:first, :order => 'created_at DESC')
  end
  
  def owned_by?(user)
    false # forums aren't owned by anyone
  end
  
  def moderated_by?(user)
    moderators.include? user
  end
  
  def moderatorship_for_user(user)
    moderatorships.find_by_user_id(user.id)
  end
  
  def find_other_forums
    Forum.find(:all, :conditions => ['id != ?', (id || 0)], :order => 'name')
  end
  
  def self.find_top
    find(:all, :conditions => 'forums.parent_id is null', :order => 'forums.position', :include => [{:topics => :posts}])
  end
  
  def depth
    ancestors.size + 1
  end
  
  def body # feed compatability
    ''
  end
  
  def self.find_visible_non_categories(user)
    find(:all, :conditions => 'category = 0', :order => 'name').select { |f| user.can_view_forum?(f) }
  end
end
